package com.leyou.cart.interceptor;

import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.cart.config.JwtProperties;
import com.leyou.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description:
 * @author: Mr_Sun
 * @Date: 2018/9/25
 * @Time: 19:32
 */
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private JwtProperties jwtProperties;

    private static final ThreadLocal<UserInfo> threadLocal = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从cookie中 获取token
        String token = CookieUtils.getCookieValue(request, this.jwtProperties.getCookieName());
        //判断token是否为空
        if (StringUtils.isEmpty(token)) {
            //如果为空  重定向到登录   登录完毕之后再回来
            response.sendRedirect("http://www.leyou.com/login.html?returnUrl=http://www.leyou.com/cart.html");
        }
        try {
            //解析token
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.jwtProperties.getPublicKey());
            //保存到线程变量
            threadLocal.set(userInfo);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            //有异常重定向到登录页面
            response.sendRedirect("http://www.leyou.com/login.html?returnUrl=http://www.leyou.com/cart.html");
        }
        return false;
    }

    public static UserInfo get() {
        return threadLocal.get();
    }
    //因为当前线程结束后,又回到了线程池   所以必须得释放

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //释放线程池变量   跟线程无关  删除的线程池的局部变量
        threadLocal.remove();

    }
}
